import React, { PureComponent } from 'react'
import { TransitionGroup, CSSTransition } from 'react-transition-group'
import './style.css'

export class App extends PureComponent {
  constructor() {
    super()
    this.state = {
      books: [
        { name: 'abc', price: 99, id: 1 },
        { name: 'cbad', price: 919, id: 2 },
        { name: 'nbc', price: 199, id: 3 },
      ],
    }
  }

  addNewBook() {
    const books = [...this.state.books]
    books.push({
      name: 'react高级设计',
      price: 123,
      id: parseInt(Math.random() * 1000),
    })
    this.setState({ books })
  }

  delBook(index) {
    const books = [...this.state.books]
    books.splice(index, 1)
    this.setState({ books })
  }

  render() {
    const { books } = this.state

    return (
      <div>
        <h2>书籍列表</h2>
        {/* TransitionGroup: 列表动画 */}
        <TransitionGroup component="ul">
          {books.map((item, index) => (
            <CSSTransition key={index} classNames="book" timeout={1000}>
              <li>
                {item.name} - {item.price}
                <button onClick={(e) => this.delBook(index)}>删除</button>
              </li>
            </CSSTransition>
          ))}
        </TransitionGroup>

        <button onClick={(e) => this.addNewBook()}>添加新书籍</button>
      </div>
    )
  }
}

export default App
